<?php
if( !defined( 'PHPCRON' ) ): define( 'PHPCRON', 1 );
if( !defined( 'FILE_ROOT' ) ) include_once( '../../_prerun' );

class PhpCron
	{
	private $frame_time, $timing;
	private $permitted_frame_time = array(	'minute', 'hour', 'day', 'week', 'month', 'year' );
	private $frame_times = array(	60, 3600, 86400, 604800, 2592000, 31536000 );
	private $registered = array();
	
	
	public function __construct( $frame_time )
		{
		$this->frame_time = trim( preg_replace( '/([0-9]+)?([\s]+)?([a-z]+)/', '\\3', $frame_time ) );
		$this->timing = trim( preg_replace( '/([0-9]+)?([\s]+)?([a-z]+)/', '\\1', $frame_time ) );
		}
	
		
	public function register( $classname, $callback )
		{
		if( !array_key_exists( $classname.$callback, $this->registered ) )
			{
			$this->registered[ $classname.$callback ] = array( 'class' => $classname, 'call' => $callback );
			}
		}
	
		
	public function getFilename()
		{
		if( empty( $this->timing ) )
			return FILE_ROOT . '__cron_' . $this->frame_time;
		else
			return FILE_ROOT . '__cron_' . $this->timing . '_' . $this->frame_time;
		}
	
		
	public function run()
		{
		$timing = $this->timing;
		if( empty( $this->timing ) )
			$timing = 1;

		$fname = $this->getFilename();
		if( file_exists( $fname ) )
			{
			$date_next = strtotime( '+' . $this->timing . ' ' . $this->frame_time, filectime( $fname ) );
			if( time() >= $date_next )
				{
				$this->updateRegistered();
				unlink( $fname );
				touch( $fname );
				}
			}
		else
			touch( $fname );
		}
	
		
	public function updateRegistered()
		{
		foreach( $this->registered as $key => $register )
			{
			eval( "{$register['class']}::{$register['call']}();" );
			}
		}
		
	public function clean()
		{
		$fname = $this->getFilename();
		if( file_exists( $fname ) )
			{
			unlink( $fname );
			}
		}
	}

endif;
?>